﻿using Microsoft.AspNetCore.Mvc;
using System.Reflection;
using IService;
using Service;
using Entity;

namespace XingWeDaWMSProject.Controllers
{
    public class SupplierController : Controller
    {
        // 注入服务
        private readonly ISupplierManagementService _supplierService;
        private readonly IPublicAttachmentsService _attachmentService;
        private readonly IWebHostEnvironment _webHostEnv; // 用于获取wwwroot路径

        // 构造函数注入
        public SupplierController(
            ISupplierManagementService supplierService,
            IPublicAttachmentsService attachmentService,
            IWebHostEnvironment webHostEnv)
        {
            _supplierService = supplierService;
            _attachmentService = attachmentService;
            _webHostEnv = webHostEnv;
        }

        public IActionResult Index()
        {
            if (Request.Headers["X-Requested-With"] == "XMLHttpRequest")
            {   
                // AJAX请求：返回部分视图（无布局）
                return PartialView();
            }
            else
            {
                // 普通请求：返回完整视图（带布局）
                return View();
            }
        }

        public IActionResult AddPage()
        {
            if (Request.Headers["X-Requested-With"] == "XMLHttpRequest")
            {
                // AJAX请求：返回部分视图（无布局）
                return PartialView();
            }
            else
            {
                // 普通请求：返回完整视图（带布局）
                return View();
            }
        }

        /// <summary>
        /// 获取供应商分页列表（供前端表格展示）
        /// </summary>
        [HttpGet]
        public async Task<IActionResult> GetSupplierList(
            string supplierName = null,
            string status = null,
            int? industryId = null,
            string managerName = null,
            int currentPage = 1,  // 默认第1页
            int pageSize = 10)    // 默认每页10条
        {
            try
            {
                // 调用服务层获取分页数据
                var paginationResult = await _supplierService.GetAllSuppliersAsync(
                    supplierName, status, industryId, managerName, currentPage, pageSize);

                // 返回规范格式（前端可直接解析）
                return Json(new
                {
                    success = true,
                    data = paginationResult.items,  // 当前页数据
                    total = paginationResult.total, // 总条数
                    message = "查询成功"
                });
            }
            catch (Exception ex)
            {
                return Json(new
                {
                    success = false,
                    data = new List<SupplierListDTO>(),
                    total = 0,
                    message = $"查询失败：{ex.Message}"
                });
            }
        }
        
        /// <summary>
        /// 为其他页面的供应商下拉框提供数据
        /// </summary>
        /// <returns></returns>
        public async Task<IActionResult> GetSupplierList2()
        {
            var paginationResult = await _supplierService.GetAllSuppliersAsync();
            // 返回规范格式（前端可直接解析）
            return Json(new
            {
                success = true,
                data = paginationResult,
                message = "查询成功"
            });
        }

        /// <summary>
        /// 新增供应商
        /// </summary>
        [HttpPost]
        public async Task<IActionResult> AddSupplier([FromForm] SupplierAddRequest request)
        {
            try
            {
                // 1. 基础参数校验
                if (string.IsNullOrEmpty(request.supplier_name))
                {
                    return Json(new { success = false, message = "供应商名称不能为空" });
                }
                if (string.IsNullOrEmpty(request.annex_code)) // 校验附件编号是否存在
                {
                    return Json(new { success = false, message = "请上传附件" });
                }

                // 2. 组装供应商数据（通过annex_code关联附件）
                var supplier = new WMSBasicSupplierManagement
                {
                    supplier_code = request.supplier_code,
                    supplier_name = request.supplier_name,
                    indInd = request.indInd,
                    supplier_classification = request.supplier_classification,
                    contact_person = request.contact_person,
                    contact_phone_number = request.contact_phone_number,
                    email_address = request.email_address,
                    purchasing_department_id = request.purchasing_department_id,
                    purchasing_manager_id = request.purchasing_manager_id,
                    suppliers_address = request.suppliers_address,
                    account_name = request.account_name,
                    taxid = request.taxid,
                    bank_account = request.bank_account,
                    opening_bank = request.opening_bank,
                    bkaddr = request.bkaddr,
                    status = request.status,
                    note = request.note,
                    create_by = request.create_by,
                    create_time = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"),
                    annex_code = request.annex_code // 关联附件编号
                };
                await _supplierService.AddAsync(supplier);

                // 3. 返回成功结果
                return Json(new { success = true, message = "新增供应商成功" });
            }
            catch (Exception ex)
            {
                return Json(new { success = false, message = $"服务器错误：{ex.Message}" });
            }
        }

        /// <summary>
        /// 处理附件上传的接口
        /// </summary>
        /// <param name="file"></param>
        /// <returns></returns>
        [HttpPost("api/Supplier/UploadFile")]
        public async Task<IActionResult> UploadFile(IFormFile file)
        {
            try
            {
                // 1. 校验文件是否为空
                if (file == null || file.Length == 0)
                {
                    return Json(new { success = false, message = "请选择要上传的文件" });
                }

                // 2. 生成唯一附件编号（用于关联供应商）
                string annexCode = Guid.NewGuid().ToString("N");

                // 3. 定义文件保存路径（wwwroot/Uploads/Supplier）
                string saveDir = Path.Combine(_webHostEnv.WebRootPath, "Uploads", "Supplier");
                if (!Directory.Exists(saveDir))
                {
                    Directory.CreateDirectory(saveDir); // 目录不存在则创建
                }

                // 4. 生成带唯一标识的文件名（避免重名）
                string fileName = $"{annexCode}_{Path.GetFileName(file.FileName)}";
                string fullPath = Path.Combine(saveDir, fileName);

                // 5. 保存文件到磁盘
                using (var stream = new FileStream(fullPath, FileMode.Create))
                {
                    await file.CopyToAsync(stream);
                }

                // 6. 构造“附件记录”并插入数据库
                var attachment = new SysOrgPublicAttachments
                {
                    annex_code = annexCode,               // 与供应商关联的附件编号
                    type_of_business = "Supplier",        // 业务类型（标识是“供应商”的附件）
                    order_no = "",                        // 可后续关联供应商编码（当前先空）
                    upload_image = fullPath.Replace(_webHostEnv.WebRootPath, "").Replace("\\", "/"), // 存储相对路径
                    uploader = 1,                         // 上传人ID（临时写死，需后续从登录态获取）
                    create_by = "admin",                  // 创建人（临时写死，需后续从登录态获取）
                    create_time = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"), // 创建时间
                    attachment = annexCode // 关键：给attachment赋值（用附件编号或其他有意义的值）
                };
                await _attachmentService.AddAsync(attachment); // 调用服务层插入数据库

                // 7. 返回成功结果（包含附件编号，供后续关联供应商）
                return Json(new
                {
                    success = true,
                    data = new { annex_code = annexCode },
                    message = "文件上传成功"
                });
            }
            catch (Exception ex)
            {
                return Json(new
                {
                    success = false,
                    message = $"上传失败：{ex.Message}"
                });
            }
        }


        /// <summary>
        /// 供应商详情页
        /// </summary>
        /// <param name="code">供应商编号（从URL参数接收）</param>
        /// <returns>详情页视图</returns>
        public IActionResult DetailsPage(string code)
        {
            ViewBag.SupplierCode = code;
            if (Request.Headers["X-Requested-With"] == "XMLHttpRequest")
            {
                // AJAX请求：返回部分视图（无布局）
                return PartialView();
            }
            else
            {
                // 普通请求：返回完整视图（带布局）
                return View();
            }
        }

        /// <summary>
        /// 根据供应商编号获取详情
        /// </summary>
        [HttpGet("api/Supplier/GetSupplierDetail")]
        public async Task<IActionResult> GetSupplierDetail(string code)
        {
            
            try
            {
                if (string.IsNullOrEmpty(code))
                {
                    return Json(new { success = false, message = "供应商编号不能为空" });
                }

                var supplier = await _supplierService.GetSupplierByCodeAsync(code);
                if (supplier == null)
                {
                    return Json(new { success = false, message = "未找到该供应商" });
                }

                return Json(new { success = true, data = supplier });
            }
            catch (Exception ex)
            {
                return Json(new { success = false, message = $"查询失败：{ex.Message}" });
            }
        }

        /// <summary>
        /// 根据供应商ID获取详情
        /// </summary>
        [HttpGet("api/Supplier/GetSupplierByIdDetail")]
        public async Task<IActionResult> GetSupplierByIdDetail(long code)
        {
            try
            {
                var supplier = await _supplierService.GetSupplierByIdAsync(code);
                if (supplier == null)
                {
                    return Json(new { success = false, message = "未找到该供应商" });
                }

                return Json(new { success = true, data = supplier });
            }
            catch (Exception ex)
            {
                return Json(new { success = false, message = $"查询失败：{ex.Message}" });
            }
        }


        /// <summary>
        /// 供应商编辑页
        /// </summary>
        /// <param name="code">供应商编号（从URL参数接收）</param>
        /// <returns>详情页视图</returns>
        public IActionResult EditPage(string code)
        {
            ViewBag.SupplierCode = code;
            if (Request.Headers["X-Requested-With"] == "XMLHttpRequest")
            {
                // AJAX请求：返回部分视图（无布局）
                return PartialView();
            }
            else
            {
                // 普通请求：返回完整视图（带布局）
                return View();
            }
        }


        /// <summary>
        /// 根据附件编号查询附件列表
        /// </summary>
        [HttpGet("api/Supplier/GetAttachments")]
        public async Task<IActionResult> GetAttachments(string annexCode)
        {
            try
            {
                if (string.IsNullOrEmpty(annexCode))
                {
                    return Json(new { success = false, message = "附件编号不能为空" });
                }

                // 从数据库查询附件
                var attachments = await _attachmentService.GetByAnnexCodeAsync(annexCode);

                // 格式化返回数据（适配前端el-upload）
                var result = attachments.Select(a => new
                {
                    id = a.attachment_id,
                    fileName = Path.GetFileName(a.upload_image), // 提取文件名
                    fileUrl = a.upload_image // 附件存储路径（需确保前端可访问）
                }).ToList();

                return Json(new { success = true, data = result });
            }
            catch (Exception ex)
            {
                return Json(new { success = false, message = ex.Message });
            }
        }


        /// <summary>
        /// 修改供应商
        /// </summary>
        [HttpPost("api/Supplier/UpdateSupplier")]
        public async Task<IActionResult> UpdateSupplier([FromForm] SupplierAddRequest request)
        {
            try
            {
                if (string.IsNullOrEmpty(request.supplier_code))
                {
                    return Json(new { success = false, message = "供应商编码不能为空" });
                }

                // 转换请求模型为实体
                var supplier = new WMSBasicSupplierManagement
                {
                    supplier_code = request.supplier_code,
                    supplier_name = request.supplier_name,
                    indInd = request.indInd,
                    supplier_classification = request.supplier_classification,
                    contact_person = request.contact_person,
                    contact_phone_number = request.contact_phone_number,
                    email_address = request.email_address,
                    purchasing_department_id = request.purchasing_department_id,
                    purchasing_manager_id = request.purchasing_manager_id,
                    suppliers_address = request.suppliers_address,
                    account_name = request.account_name,
                    taxid = request.taxid,
                    bank_account = request.bank_account,
                    opening_bank = request.opening_bank,
                    bkaddr = request.bkaddr,
                    status = request.status,
                    note = request.note,
                    update_by = "admin",  // 实际应从登录用户获取
                    annex_code = request.annex_code
                };

                await _supplierService.UpdateAsync(supplier);
                return Json(new { success = true, message = "修改供应商成功" });
            }
            catch (Exception ex)
            {
                return Json(new { success = false, message = $"修改失败：{ex.Message}" });
            }
        }

        /// <summary>
        /// 删除供应商（逻辑删除）
        /// </summary>
        [HttpPost("api/Supplier/Delete")]
        public async Task<IActionResult> Delete(string supplier_code)
        {
            try
            {
                if (string.IsNullOrEmpty(supplier_code))
                {
                    return Json(new { success = false, message = "供应商编码不能为空" });
                }
                
                await _supplierService.Delete(supplier_code);
                return Json(new { success = true, message = "删除供应商成功" });
            }
            catch (Exception ex)
            {
                return Json(new { success = false, message = $"删除失败：{ex.Message}" });
            }
        }

    }
}
